<template>
  <div class="production-plan">
    <el-form-item #default="scope">
      <el-button type="primary" @click="addjihau">保存</el-button>

    </el-form-item>
    <!-- 基本信息 -->
    <!-- 标题 -->
    <div class="title-container">
      <h3 class="title">生产领料</h3>
    </div>

    <!-- 基本信息表单 -->
    <el-card class="form-card">
      <template #header>
        <div class="card-header">基本信息</div>
      </template>
      <el-form class="basic-info-form" :model="formData" :rules="rules" label-width="120px" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="单据主题" prop="documentSubject">
              <el-input v-model="formData.documentSubject" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="单据编号" prop="documentNo">
              <el-input v-model="formData.documentNo" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="*领料日期" prop="pickingDate">
              <el-date-picker
                v-model="formData.pickingDate"
                type="date"
                required
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="来源数据类型" prop="documentType">
              <el-input v-model="formData.documentType" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="来源单据" prop="documentSource">
              <el-input v-model="formData.documentSource" type="textarea" />
            </el-form-item>
          </el-col>
           <el-col :span="10">
              <el-form-item label="领料数量合计">
                <el-input-number v-model="formData.pickingNumber" placeholder="请输入数量" :min="0" :step="1" />
              </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="制单日期" prop="produceDate">
              <el-date-picker
                v-model="formData.produceDate"
                type="date"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="制单人员" prop="produceName">
              <el-input v-model="formData.produceName" type="textarea"  />
            </el-form-item>
          </el-col>

           <el-col :span="10">
            <el-form-item label="关联项目">
              <el-select v-model="formData.relatedProject" placeholder="请选择单位">
                <el-option label="生产领料" value="生产领料信息" />
                <el-option label="采购领料" value="采购领料信息" />
                <el-option label="生产补料" value="生产补料信息" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="备注" prop="pickingNote">
              <el-input v-model="formData.pickingNote" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    

        <!-- 标题 -->
    <div class="page-title">
      <h2>领料明细</h2>
    </div>

    <!-- 物料明细 -->
    <div class="detail-section">
      <h4 class="sub-title">领料明细</h4>
      <el-button size="small" @click="addNewRow">新增行</el-button>
      <el-button size="small"  @click="batchSaveDetails"> 批量保存明细</el-button>
      <el-table :data="planDetailsList" border style="width: 100%">
        <el-table-column label="产品名称">
          <template #default="{ row }">
            <el-input v-model="row.productName" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="产品编号">
          <template #default="{ row }">
            <el-input v-model="row.productCode" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="型号">
          <template #default="{ row }">
            <el-input v-model="row.model" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单位">
          <template #default="{ row }">
            <el-input v-model="row.unit" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
         <el-table-column label="领料数量">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.issueQuantity" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="出库库管">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.warehouse" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>
         <el-table-column label="现有库存">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.currentStock" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="交货日期">
            <template #default="{ row }">
               <el-date-picker
                   v-model="row.deliveryDate"
                    type="date">
                </el-date-picker>
            </template>
        </el-table-column>
           <el-table-column label="备注">
          <template #default="{ row }">
            <el-input v-model="row.remarks" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="领料方式">
          <template #default="{ row }">
            <el-input v-model="row.pickupMethod" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
      

        <el-table-column label="关联单据">
          <template #default="{ row }">
            <el-input v-model="row.relatedDoc" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #default="{ row }">
            <!-- <el-button size="small" @click="saveSingleDetail(row)" :disabled="row.isSaved">保存本条</el-button> -->
              <el-button size="small" type="success" @click="UpdateDetail(row)">修改</el-button> 
            <el-button size="small" type="danger" @click="deleteDetail(row)" :disabled="row.isSaved">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

        <!-- 附件部分 -->

        <div class="attachment-section">
            <h4 class="sub-title">附件管理</h4>
            <el-button size="small" @click="batchUpload">批量上传</el-button>
            <el-table :data="attachments" border style="width: 100%">
                <el-table-column label="文件名称" prop="fileName"></el-table-column>
                <el-table-column label="文件大小" prop="fileSize"></el-table-column>
                <el-table-column label="上传人" prop="uploader"></el-table-column>
                <el-table-column label="上传时间" prop="uploadTime"></el-table-column>
            </el-table>
        </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import {Materialwrite,Materialread} from '@/axios/axiosHelper'
import axios from 'axios';

const formRef = ref(null);
const currentUser = ref("admin"); 
const router = useRouter();
const route = useRoute();

// 主表单数据
const formData = reactive({
  pickingId:'',
  documentSubject: "",
  documentNo: "",
  pickingDate: "",
  documentType: "",
  documentSource: "",
  pickingNumber: '',
  produceDate: "",
  produceName: currentUser.value,
  relatedProject: "",
  pickingNote: "",
});

// 主表单验证规则

const rules = reactive({
  documentSubject: [
    { required: true, message: '单据主题不能为空', trigger: 'blur' }
  ],
  pickingDate: [
    { required: true, message: '领料日期不能为空', trigger: 'blur' }
  ],
});

// 明细数据列表
const planDetailsList = ref([]);

const attachments = ref([]);

// 监听路由参数变化
watch(() => route.query, async (newQuery) => {
    if (newQuery.pickingId) {
        await getProductionById(newQuery.pickingId);
    } else {
        // 清空表单
        formData.documentSubject = "";
        formData.documentNo = "";
        formData.produceName = currentUser.value;
        formData.documentType = "";
        formData.pickingDate = "";
        formData.documentSource = "";
        formData.pickingNumber = "";
        formData.produceDate = "";
        formData.relatedProject = "";
        formData.pickingNote = "";
        formData.pickingId = null;
        planDetailsList.value = [];
    }mainData
});

const getProductionById = async (pickingId) => {
    try {
        const [mainResponse, detailResponse] = await Promise.all([
        Materialread.get('/l-read/api/GetValues/FTMaterialsPicking', {
                params: { PickingId: pickingId }
            }),
            Materialread.get('/l-read/api/GetValues/Handle', {
                params: { detailID: pickingId }
            })
        ]);

        if (mainResponse.data.code === 200) {
            const mainData = mainResponse.data.data[0];
            formData.documentSubject = mainData.documentSubject;
            formData.documentNo = mainData.documentNo;
            formData.pickingDate = mainData.pickingDate;
            formData.documentType = mainData.documentType;
            formData.documentSource = mainData.documentSource;
            formData.pickingNumber = mainData.pickingNumber;
            formData.produceDate = mainData.produceDate;
            formData.produceName = mainData.produceName;
            formData.relatedProject = mainData.relatedProject;
            formData.pickingNote = mainData.pickingNote;
            formData.pickingId = mainData.pickingId;

        }
        if (detailResponse.data.code === 200) {
            planDetailsList.value = detailResponse.data.data.map(item => ({
                detailID: item.detailID || "",
                productName: item.productName || "",
                productCode: item.productCode || "",
                model: item.model || "",
                unit: item.unit || "",
                issueQuantity: item.issueQuantity || 0,
                warehouse: item.warehouse || 0,
                currentStock: item.currentStock || 0,
                deliveryDate: item.deliveryDate || "",
                remarks: item.remarks || "",
                pickupMethod: item.pickupMethod || "",
                relatedDoc: item.relatedDoc || "",
                issueID: item.issueID || null,
                pickingId: item.pickingId || '',
              }));
        }
    } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('数据加载失败，请检查网络或联系管理员');
    }
};

// 保存主表单
const addjihau1 = async () => {
    try {
        const response = await axios.put('', formData);
        if (response.data.code === 400) {
            formData.pickingId = response.data.data.pickingId;
            ElMessage.success('主表单保存成功');
        } else {
            ElMessage.error(`主表单保存失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('保存错误:', error);
        ElMessage.error('保存失败，请检查网络或联系管理员');
    }
};
// 保存主表单和明细
const addjihau = async () => {
  if (formRef.value) {
    const isValid = await formRef.value.validate();
    if (isValid) {
      try {
        // 保存主表单
        const response = await axios.put('https://localhost:7077/api/Ment/UpdateMaterialsPicking', formData);
        if (response.data.code === 400) {
          formData.pickingId = response.data.data.pickingId;
          ElMessage.success('主表单保存成功');

          // 保存明细
          const saveDetailPromises = planDetailsList.value.map(async (row) => {
            const detailWithId = {
              ...row,
              detailID: formData.pickingId
            };
            const detailResponse = await axios.put(
              'https://localhost:7077/api/Ment/UpdateMaterialsPickingDetail',
              detailWithId
            );
            if (detailResponse.data.code === 400) {
              row.isSaved = true;
              return true;
            } else {
              ElMessage.error(`明细保存失败：${detailResponse.data.message}`);
              return false;
            }
          });

          const results = await Promise.all(saveDetailPromises);
          if (results.every(result => result)) {
            ElMessage.success('所有明细保存成功');
            router.push('/ShowMaterialsPicking');
          }
        } else {
          ElMessage.error(`主表单保存失败：${response.data.message}`);
        }
      } catch (error) {
        console.error('保存过程中发生错误:', error.response?.data);
        ElMessage.error('保存过程中发生错误，请检查网络或联系管理员');
      }
    }
  }
};
// 新增行
const addNewRow = () => {
  planDetailsList.value.push({
  detailID: null,
  productName: "",
  productCode: "",
  model: "",
  unit: "",
  issueQuantity: 0,
  warehouse: 0,
  currentStock: 0,
  deliveryDate: "",
  remarks: "",
  pickupMethod: "",
  relatedDoc: "",
  issueID: null,
  pickingId: null,
  isDel: true
  });
};


// 批量保存明细
const batchSaveDetails = async () => {
    // if (!formData.pickingId) {
    //     ElMessage.warning('请先保存主表单');
    //     return;
    // }

    const detailsWithId = planDetailsList.value.map(detail => ({
        ...detail,
        pickingId: formData.pickingId,
    }));

    try {
        const response = await axios.put(
            'https://localhost:7077/api/Ment/UpdateMaterialsPickingDetail',
            detailsWithId
        );
        if (response.data.code === 400) {
            // 更新 planDetailsList 中的 productionScheduleDetailId
            planDetailsList.value = response.data.data.map((item, index) => ({
                ...planDetailsList.value[index],

                  pickingId: item.pickingId
            }));
            ElMessage.success('明细批量保存成功');
        } else {
            ElMessage.error(`明细批量保存失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('保存错误:', error);
        ElMessage.error('保存失败，请检查网络或联系管理员');
    }
};

// 修改单条明细
const UpdateDetail = async (row) => {
    // if (!formData.pickingId) {
    //     ElMessage.warning('请先保存主表单');
    //     return;
    // }

    // const detailData = {
    //     ...row,
    //     pickingId: formData.pickingId
    // };

    console.log('发送给后端的明细数据:', detailData); // 打印发送给后端的数据

    try {
        const response = await Materialwrite.put(
            '/l-wirth/api/Ment/UpdateMaterialsPickingDetail',
            detailData
        );
        console.log('后端返回的响应:', response); // 打印后端返回的响应

        if (response.data.code === 400) {
            ElMessage.success('明细更新成功');
        } else {
            ElMessage.error(`更新失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('更新错误:', error);
        ElMessage.error('更新失败，请检查网络或联系管理员');
    }
};

// 删除单条明细
const deleteDetail = (row) => {
    ElMessageBox.confirm('确认删除该条明细？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const index = planDetailsList.value.indexOf(row);
        if (index !== -1) {
            planDetailsList.value.splice(index, 1);
            ElMessage.success('明细删除成功');
        }
    }).catch(() => {
        ElMessage.info('取消删除');
    });
};

const batchUpload = () => {
    ElMessageBox.confirm('确认上传选中文件？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        ElMessage.info('批量上传功能待完善具体逻辑');
    });
};



onMounted(() => {
    if (route.query.pickingId) {
        getProductionById(route.query.pickingId);
    }
});
</script>

<style scoped>
.production-plan {
    padding: 20px;
}

.title {
    text-align: center;
    margin-bottom: 20px;
}

.sub-title {
    margin: 20px 0 10px;
    font-size: 16px;
    font-weight: 500;
}

.detail-section,
.attachment-section {
    margin-top: 20px;
}

.el-table {
    margin-top: 10px;
}
</style>    